﻿(function ($) {

	$.fn.FixedHeadTable = function () {

		return this.each(function () {

			var $this = $(this);

			var $outer_div_id = "_main_" + $this.attr("ID");
			var $main_div_id = "_content_" + $this.attr("ID");
			var $head_div_id = "_head_div_" + $this.attr("ID");

			if (!$this.hasClass('FixedHeadTable')) {

				$this.addClass('FixedHeadTable');

				$this.wrap('<div id="' + $outer_div_id + '"><div id="' + $main_div_id + '"></div></div>');

				$("#" + $outer_div_id).addClass("fixed");
				$("#" + $main_div_id).addClass("fixed-content").after('<div id="' + $head_div_id + '"></div>');

				var $head_div = $('#' + $head_div_id);

				// 拷贝表头,并且指定样式,并移除tbody内容
				$head_div.append($(this).clone().attr("id", "_head_" + $this.attr("ID"))).addClass('fixed-head');
				$('table tbody,table tfoot', $head_div).remove();

				$(window).resize(function () { resizer($this, $head_div, $('table thead th', $head_div)); });
			}
			var $head_div = $('#' + $head_div_id);
			resizer($this, $('#' + $head_div_id), $('table thead th', $head_div));
		});
	};

	function resizer($this, $head_div, $head) {
		var width = $head_div.width();
		$this.width(width);
		$("#_head_" + $this.attr("ID")).width(width);

		//var widths = new Array();
		var $this_head = $("thead tr th", $this);
		//var cnt = $head.length - 1;
		$this_head.each(function (i) {
			$($head[i]).width($(this).width() - 1);
			/*widths.push($(this).width() - 1);*/
		});
		//widths[0] = widths[0] - 1;

		//$this_head.each(function (i) {
		//if (i < cnt) {
		//$(this).width(widths[i]);
		//$($head[i]).width(widths[i]);
		//}
		//});
	}

})(jQuery);